package com.xsf.pay.service.impl;


import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.xsf.pay.common.domain.CodeMsg;
import com.xsf.pay.common.domain.ResultData;
import com.xsf.pay.common.exception.BusinessRunTimeException;
import com.xsf.pay.service.RedisService;
import com.xsf.pay.service.TokenService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

/**
 * @author daimao
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Resource
    private RedisService redisService;

    @Override
    public ResultData<Object> createToken() {
        //生成uuid当作token
        String token = UUID.randomUUID().toString();
        //将生成的token存入redis中
        redisService.set(token, token);
        //返回正确的结果信息
        return ResultData.success(token);
    }

    @Override
    public void checkToken(HttpServletRequest request) {
        //从请求头中获取token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            //如果请求头token为空就从参数中获取
            token = request.getParameter("token");
            //如果都为空抛出参数异常的错误
            if (StrUtil.isBlank(token)) {
                throw new BusinessRunTimeException(CodeMsg.ILLEGAL_ARGUMENT);
            }
        }
        //如果redis中不包含该token，说明token已经被删除了，抛出请求重复异常
        if (!redisService.hasKey(token)) {
            throw new BusinessRunTimeException(CodeMsg.REPETITIVE_OPERATION);
        }
        //删除token
        Boolean del = redisService.delete(token);
        //如果删除不成功（已经被其他请求删除），抛出请求重复异常
        if (!del) {
            throw new BusinessRunTimeException(CodeMsg.REPETITIVE_OPERATION);
        }
    }
}
